package com.ylyq.ylxx.quarz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ylyq.ylxx.constants.AccountConstant;
import com.ylyq.ylxx.context.FilterContextHandler;
import com.ylyq.ylxx.entity.*;
import com.ylyq.ylxx.lingo.ILingoService;
import com.ylyq.ylxx.model.ResponseData;
import com.ylyq.ylxx.model.bean.*;
import com.ylyq.ylxx.model.request.*;
import com.ylyq.ylxx.service.*;
import com.ylyq.ylxx.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ini4j.Wini;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @ClassName SchedulerTask
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/8/4 9:57
 * @Version 1.0
 */
//每隔5秒执行一次：*/5 * * * * ?
//
//每隔10分钟执行一次：0 */10 * * * ?
//
//每天23点执行一次：0 0 23 * * ?
//
//    每天23点40执行一次：0 40 23 * * ?
//每天凌晨1点执行一次：0 0 1 * * ?
//
//每月1号凌晨1点执行一次：0 0 1 1 * ?
//
//每月最后一天23点执行一次：0 0 23 L * ?
//
//每周星期天凌晨1点实行一次：0 0 1 ? * L
//
//在26分、29分、33分执行一次：0 26,29,33 * * * ?
//
//每天的0点、13点、18点、21点都执行一次：0 0 0,13,18,21 * * ?
@Slf4j
@Component
public class SchedulerTask {
    @Value("${public.config.python.pythonPath}")
    private String pythonPath;
    @Value("${public.config.python.pythonSuffix}")
    private String pythonSuffix;

    @Autowired
    private IYlyqPlanStopStartService iYlyqPlanStopStartService;
    @Autowired
    private IYlyqCreativeTitleService iYlyqCreativeTitleService;
    @Autowired
    private IYlyqCreativeTitleV2Service iYlyqCreativeTitleV2Service;
    @Autowired
    private IYlyqCreativeVideoMaterialService iYlyqCreativeVideoMaterialService;
    @Autowired
    private IYlyqRefusePlanService iYlyqRefusePlanService;
    @Autowired
    private IOceaneginePlanService iOceaneginePlanService;
    @Autowired
    private IOceanegineGroupService iOceanegineGroupService;
    @Autowired
    private IOceanegineCreativeService iOceanegineCreativeService;
    @Autowired
    private IOceanegineReportService iOceanegineReportService;
    @Autowired
    private IYlyqPlanStatusService iYlyqPlanStatusService;
    @Autowired
    private IOceanengineToolService iOceanengineToolService;
    @Autowired
    private ILingoService iLingoService;
    @Autowired
    private RedisUtil redisUtils;
    @Autowired
    private IOauthService iOauthService;
    @Autowired
    private IYlyqPlanBidBudgetService iYlyqPlanBidBudgetService;
    @Autowired
    private IYlyqGroupInfoService iYlyqGroupInfoService;
    @Autowired
    private IOceanegineService iOceanegineService;
    @Autowired
    private IYlyqBudgetService iYlyqBudgetService;

    /**
     * @return void
     * @Author xiaweichao
     * @Description //TODO 每天23：40执行，智能启停 * @Date 10:02 2020/8/4,要在24点前执行，因为要保存一份计划的预算和出价，供雷达打分用
     * @Param []
     **/
//    @Scheduled(cron = "0 57 23 * * ?")
    @Scheduled(cron = "0 0 1,9,19 * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    private void smartStopAndStart() {
        log.info("智能启停开始了=====");
        iYlyqPlanBidBudgetService.deleteAll(null);
//        ExecutorService executorService = Executors.newCachedThreadPool();
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        QueryWrapper<YlyqPlanStopStart> queryWrapperPlan = new QueryWrapper<>();
        queryWrapperPlan.select("advertiser_id", "user_id", "group_id", "plan_id");
        List<YlyqPlanStopStart> listPlanStopStart = iYlyqPlanStopStartService.list(queryWrapperPlan);
        if (null == listPlanStopStart || listPlanStopStart.isEmpty())
            return;
//        //list分组,根据advertiser_id分组
//        Map<Long, List<YlyqPlanStopStart>> collectPlanStopStart = listPlanStopStart.stream().collect(Collectors.groupingBy(YlyqPlanStopStart::getAdvertiserId));
        //list分组,根据group_id分组
        Map<Long, List<YlyqPlanStopStart>> collectPlanStopStart = listPlanStopStart.stream().collect(Collectors.groupingBy(YlyqPlanStopStart::getGroupId));

        QueryWrapper<YlyqGroupInfo> groupInfoQueryWrapper = new QueryWrapper<>();
        groupInfoQueryWrapper.in("group_id", collectPlanStopStart.keySet());
        List<YlyqGroupInfo> ylyqGroupInfos = iYlyqGroupInfoService.list(groupInfoQueryWrapper);
        Map<Long, List<YlyqGroupInfo>> collectGroupList = ylyqGroupInfos.stream().collect(Collectors.groupingBy(YlyqGroupInfo::getGroupId));

        for (Map.Entry<Long, List<YlyqPlanStopStart>> entry : collectPlanStopStart.entrySet()) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<YlyqPlanStopStart> list = entry.getValue();
//            Long advertiser = entry.getKey();
                        Long advertiser = list.get(0).getAdvertiserId();
                        Long groupId = entry.getKey();

                        if (null == list || list.isEmpty()) {
                            return;
                        }
                        String userId = list.get(0).getUserId();
                        //在线程里保存所用的access_token。如果refresh_token 过期了就无法进行启停监控了
                        String access_token = (String) redisUtils.get("access_token" + userId);
                        if (StringUtils.isBlank(access_token)) {
                            String refresh_token = (String) redisUtils.get("refresh_token" + userId);
                            if (StringUtils.isBlank(refresh_token)) {
                                log.error("refresh_token 过期：{}", refresh_token);
                                return;
                            }
                            String accessToken = iOauthService.reFreshAccessToken(userId, refresh_token);
                            FilterContextHandler.setOceaneToken(accessToken);
                        } else {
                            FilterContextHandler.setOceaneToken(access_token);
                        }


                        Set<Long> collect = list.stream().map(YlyqPlanStopStart::getPlanId).collect(Collectors.toSet());
                        Long[] planId = collect.toArray(new Long[collect.size()]);
//                        Set<Long> collect1 = list.stream().map(YlyqPlanStopStart::getGroupId).collect(Collectors.toSet());
//                        Long[] groupId = collect1.toArray(new Long[collect1.size()]);

                        //获取计划的状态（模型返回的状态值）
                        QueryWrapper<YlyqPlanStatus> planStatusQueryWrapper = new QueryWrapper<>();
                        planStatusQueryWrapper.in("plan_id", planId);
                        List<YlyqPlanStatus> planStatusList = iYlyqPlanStatusService.list();
                        Map<Long, List<YlyqPlanStatus>> collectPlanStatus = planStatusList.stream().collect(Collectors.groupingBy(YlyqPlanStatus::getPlanId));


                        //获取组数据报表,用于调toufan.lingo的时候需要用到组消耗数据
                        GetReportGroupRequest getReportGroupRequest = new GetReportGroupRequest();
                        getReportGroupRequest.setAdvertiser_id(advertiser);
                        getReportGroupRequest.setPage_size(30);

                        Calendar a = Calendar.getInstance();
                        a.add(Calendar.DAY_OF_MONTH, -30);
                        String startDate = new SimpleDateFormat("YYYY-MM-dd").format(a.getTime());
                        Calendar c = Calendar.getInstance();
//                            c.add(Calendar.DAY_OF_MONTH, -1);
                        String endDate = new SimpleDateFormat("YYYY-MM-dd").format(c.getTime());

                        getReportGroupRequest.setStart_date(startDate);
                        getReportGroupRequest.setEnd_date(endDate);

                        getReportGroupRequest.setGroup_by(new String[]{"STAT_GROUP_BY_FIELD_ID"});
                        GetReportGroupRequest.FilteringGetReportGroupRequest filteringGetReportGroupRequest = new GetReportGroupRequest.FilteringGetReportGroupRequest();
                        filteringGetReportGroupRequest.setCampaign_ids(new Long[]{groupId});
                        getReportGroupRequest.setFiltering(filteringGetReportGroupRequest);

                        OceanengineReportGroupInfo reportGroup = iOceanegineReportService.getReportGroup(getReportGroupRequest);
                        List<OceanengineReportGroupInfo.DataBean.ListBean> groupListBeans = reportGroup.getData().getList();
                        if (null == groupListBeans) {
                            return;
                        }
                        Map<Long, List<OceanengineReportGroupInfo.DataBean.ListBean>> groupListBeanMap = groupListBeans.stream().collect(Collectors.groupingBy(OceanengineReportGroupInfo.DataBean.ListBean::getId));

                        //获取计划详情
                        GetPlanInfoRequest getPlanInfoRequest = new GetPlanInfoRequest();
                        getPlanInfoRequest.setAdvertiser_id(advertiser);
                        getPlanInfoRequest.setPage_size(planId.length);
                        GetPlanInfoRequest.FilteringGetPlanInfoRequest filteringGetPlanInfoRequest = new GetPlanInfoRequest.FilteringGetPlanInfoRequest();
                        filteringGetPlanInfoRequest.setIds(planId);
                        //不要加这句，会影响 iYlyqPlanStopStartService.removeByMap(removeMap);和下面过滤掉被用户在巨量手动删除的计划的操作
                        filteringGetPlanInfoRequest.setStatus("AD_STATUS_DELIVERY_OK");//已经独立放到后面定时删除处理
                        getPlanInfoRequest.setFiltering(filteringGetPlanInfoRequest);
                        OceanenginePlanInfo planInfo = iOceaneginePlanService.getPlan(getPlanInfoRequest);
                        List<OceanenginePlanInfo.DataBean.ListBean> planInfoList = planInfo.getData().getList();
                        if (null == planInfoList || planInfoList.isEmpty()) {
                            return;
                        }

                        //list分组,根据计划id分组
                        Map<Long, List<OceanenginePlanInfo.DataBean.ListBean>> collectPlanInfo = planInfoList.stream().collect(Collectors.groupingBy(OceanenginePlanInfo.DataBean.ListBean::getId));

                        //过滤掉被用户在巨量手动删除的计划，因为获取学习状态接口，传入的ids，如果有不存在的计划，就会整体报错
                        List<Long> resultPlans = Arrays.asList(planId);
                        //获取学习状态
                        //因为一次批量操作，最多处理100个id
                        List<OceanengineAdStatExtraInfo.DataBean> listAdStatExtraInfo = new ArrayList<>();
                        int m = 0;
                        while (resultPlans.size() > 100 * m) {
                            List<Long> planIdsTemp;
                            if (resultPlans.size() > 100 * (m + 1)) {
                                planIdsTemp = resultPlans.subList(m * 100, 100 * (m + 1));
                            } else {
                                planIdsTemp = resultPlans.subList(m * 100, resultPlans.size());
                            }

                            listAdStatExtraInfo.addAll(iOceanengineToolService.ad_stat_extra_info(new AdStatExtraInfoRequest(advertiser, planIdsTemp.toArray(new Long[planIdsTemp.size()]))).getData());

                            m++;
                        }
                        //学习期list分组,根据计划id分组
                        Map<Long, List<OceanengineAdStatExtraInfo.DataBean>> collectAdStatExtraInfo = listAdStatExtraInfo.stream().collect(Collectors.groupingBy(OceanengineAdStatExtraInfo.DataBean::getAd_id));

                        //获取计划数据报表
                        GetReportPlanRequest getReportRequest = new GetReportPlanRequest();
                        getReportRequest.setAdvertiser_id(advertiser);
                        getReportRequest.setPage_size(30 * planId.length);
                        getReportRequest.setStart_date(startDate);
                        getReportRequest.setEnd_date(endDate);
                        getReportRequest.setGroup_by(new String[]{"STAT_GROUP_BY_FIELD_ID", "STAT_GROUP_BY_FIELD_STAT_TIME"});
                        GetReportPlanRequest.FilteringGetReportPlanRequest filteringGetReportPlanRequest = new GetReportPlanRequest.FilteringGetReportPlanRequest();
                        filteringGetReportPlanRequest.setAd_ids(planId);
                        filteringGetReportPlanRequest.setStatus("AD_STATUS_DELIVERY_OK");
                        getReportRequest.setFiltering(filteringGetReportPlanRequest);
                        OceanengineReportPlanInfo reportPlan = iOceanegineReportService.getReportPlan(getReportRequest);

                        List<OceanengineReportPlanInfo.DataBean.ListBean> list1 = reportPlan.getData().getList();

                        //计划报告list分组,根据计划id分组
                        Map<Long, List<OceanengineReportPlanInfo.DataBean.ListBean>> reportList = list1.stream().collect(Collectors.groupingBy(OceanengineReportPlanInfo.DataBean.ListBean::getAd_id));

                        for (Map.Entry<Long, List<OceanengineReportPlanInfo.DataBean.ListBean>> entry : reportList.entrySet()) {
                            //按时间重排序，今天的排在最后，最开始时间排在第一
                            Collections.sort(entry.getValue(), new Comparator<OceanengineReportPlanInfo.DataBean.ListBean>() {
                                DateFormat f = new SimpleDateFormat("yyyy-MM-dd");

                                @SneakyThrows
                                @Override
                                public int compare(OceanengineReportPlanInfo.DataBean.ListBean o1, OceanengineReportPlanInfo.DataBean.ListBean o2) {
                                    return f.parse(o1.getStat_datetime()).compareTo(f.parse(o2.getStat_datetime()));
                                }
                            });
                        }

                        //获取创意数据报表
                        GetReportCreativeRequest getReportCreativeRequest = new GetReportCreativeRequest();
                        getReportCreativeRequest.setAdvertiser_id(advertiser);
//                        getReportCreativeRequest.setPage_size((Tools.getDayFromdateToEndDate(new SimpleDateFormat("yyyy-MM-dd").format(collectGroupList.get(groupId).get(0).getCreatedTime()),endDate)+1) * planId.length*5);
                        getReportCreativeRequest.setPage_size(1000);
//                        getReportCreativeRequest.setStart_date(startDate);

                        getReportCreativeRequest.setStart_date(new SimpleDateFormat("yyyy-MM-dd").format(collectGroupList.get(groupId).get(0).getCreatedTime()));
                        getReportCreativeRequest.setEnd_date(endDate);
                        getReportCreativeRequest.setGroup_by(new String[]{"STAT_GROUP_BY_FIELD_ID"});
                        GetReportCreativeRequest.FilteringGetReportPlanRequest filteringGetReportCreativeRequest = new GetReportCreativeRequest.FilteringGetReportPlanRequest();
                        filteringGetReportCreativeRequest.setAd_ids(planId);
//                        filteringGetReportCreativeRequest.setStatus("AD_STATUS_DELIVERY_OK");
                        getReportCreativeRequest.setFiltering(filteringGetReportCreativeRequest);
                        OceanengineReportCreativeInfo reportCreative = iOceanegineReportService.getReportCreative(getReportCreativeRequest);
                        List<OceanengineReportCreativeInfo.DataBean.ListBean> reportCreativeList = reportCreative.getData().getList();


//                        输出数据：
//                        计划总数~
//                        计划id，执行操作（0：不操作，1：修改预算，2：修改出价，3修改预算和出价，4新建计划，5新建并修改出价，6暂停），出价，预算，状态值~

                        log.info("智能启停开始了=====输入数据");

                        QueryWrapper<YlyqGroupInfo> groupInfoQueryWrapper = new QueryWrapper<>();
                        groupInfoQueryWrapper.eq("advertiser_id", advertiser);
                        groupInfoQueryWrapper.eq("group_id", groupId);
                        groupInfoQueryWrapper.select("priceForm");
                        List<Object> priceForm = iYlyqGroupInfoService.listObjs(groupInfoQueryWrapper);

                        QueryWrapper<YlyqBudget> budgetQueryWrapper = new QueryWrapper<>();
                        budgetQueryWrapper.eq("advertise_id", advertiser);
                        YlyqBudget budgetServiceOne = iYlyqBudgetService.getOne(budgetQueryWrapper);


//（计划展现数据）计划id，天数，总花费，展示数，平均千次展现费用，点击数，平均点击单价，点击率，转化数，转化成本，转化率~
//
//（计划数据）计划id，状态值(每次会输出计划的状态值，记录保存下次调用模型的时候传，如果是第一次调用该模型，为空),学习期状态（DEFAULT（3默认，不在学习期中）、LEARNING（0学习中）、LEARNED（1学习成功）、LEARN_FAILED（2学习失败)），当前出价，当前计划日预算~
//
//（创意数据）计划id，创意id，点击数，点击率~(累加的)
//
//                                客户可接受转化成本~
//                                账户当前日预算~
//                        运行时间点~
//                        日预算~
//                            周预算~
//                            总预算

                        StringBuilder dataStr=new StringBuilder();

                        for (Map.Entry<Long, List<OceanengineReportPlanInfo.DataBean.ListBean>> entry : reportList.entrySet()) {
                            Long planid = entry.getKey();
                            List<OceanengineReportPlanInfo.DataBean.ListBean> entryValue = entry.getValue();
                            //按时间重排序，今天的排在最后，最开始时间排在第一
                            Collections.sort(entryValue, new Comparator<OceanengineReportPlanInfo.DataBean.ListBean>() {
                                DateFormat f = new SimpleDateFormat("yyyy-MM-dd");

                                @SneakyThrows
                                @Override
                                public int compare(OceanengineReportPlanInfo.DataBean.ListBean o1, OceanengineReportPlanInfo.DataBean.ListBean o2) {
                                    return f.parse(o1.getStat_datetime()).compareTo(f.parse(o2.getStat_datetime()));
                                }
                            });
//                        账户id	可接受转化成本	账户总预算	账户周预算	账户日预算	计划id	计划新建时间	时间	学习期	当前出价	当前日预算	消耗	展示数	平均千次展现费用	点击数
//                        平均点击单价	点击率（%）	转化数	转化成本	转化率（%）	计划旧状态
                            for (int i = 0; i < entryValue.size(); i++) {
                                dataStr.append(advertiser+" "+priceForm.get(0)+" "+budgetServiceOne.getBudgetTotal()+" "+budgetServiceOne.getBudgetWeek()+" "+budgetServiceOne.getBudgetDay()+" "
                                        +planid+ " "+Tools.parseTime(collectPlanInfo.get(planid).get(0).getAd_create_time(),"yyyy/MM/dd")+"/"+new Date().getHours() +" "+Tools.parseTime(entryValue.get(i).getStat_datetime(),"yyyy/MM/dd") +" ");
                                switch (collectAdStatExtraInfo.get(planid).get(0).getLearning_phase()) {
                                    //DEFAULT（默认，不在学习期中）、LEARNING（学习中）、LEARNED（学习成功）、LEARN_FAILED（学习失败)
                                    case "DEFAULT":
                                        dataStr.append("3" +" ");
                                        break;
                                    case "LEARNING":
                                        dataStr.append("0" +" ");
                                        break;
                                    case "LEARNED":
                                        dataStr.append("1" +" ");
                                        break;
                                    case "LEARN_FAILED":
                                        dataStr.append("2"+" ");
                                        break;
                                }
                                dataStr.append(collectPlanInfo.get(planid).get(0).getCpa_bid() + " " + collectPlanInfo.get(planid).get(0).getBudget() + " ");
                                dataStr.append(entryValue.get(i).getCost()+" "+entryValue.get(i).getShow()+ " " + entryValue.get(i).getAvg_show_cost()+ " " + entryValue.get(i).getClick() + " "
                                        + entryValue.get(i).getAvg_click_cost() + " " + entryValue.get(i).getCtr() + " " + entryValue.get(i).getConvert() + " " +
                                        entryValue.get(i).getConvert_cost() + " " + entryValue.get(i).getConvert_rate()+" ");
                                dataStr.append(collectPlanStatus.containsKey(planid) ? collectPlanStatus.get(planid).get(0).getStatus() : "0" + "\n");//状态值

                            }
                        }

                        String planInputPath = pythonPath + SnowflakeIdWorkerUtil.generateId() + pythonSuffix;
                        File planInputFile = new File(planInputPath);
                        int planResult = BufferedWriterUtil.writerIntoFile(planInputFile, dataStr.toString());
                        if (planResult == AccountConstant.FAIL) {
                            log.error(planInputFile.getAbsolutePath() + "输入文件生成失败");
                            return;
                        }

//（计划数据）计划id，状态值(每次会输出计划的状态值，记录保存下次调用模型的时候传，如果是第一次调用该模型，为空),学习期状态（DEFAULT（3默认，不在学习期中）、LEARNING（0学习中）、LEARNED（1学习成功）、LEARN_FAILED（2学习失败)），当前出价，当前计划日预算~
                        StringBuilder inputStr=new StringBuilder();
                        for (OceanenginePlanInfo.DataBean.ListBean planTemp : planInfoList) {
                            inputStr.append(planTemp.getId() + " ");

                            switch (collectAdStatExtraInfo.get(planTemp.getId()).get(0).getLearning_phase()) {
                                //DEFAULT（默认，不在学习期中）、LEARNING（学习中）、LEARNED（学习成功）、LEARN_FAILED（学习失败)
                                case "DEFAULT":
                                    inputStr.append("3 ");
                                    break;
                                case "LEARNING":
                                    inputStr.append("0 ");
                                    break;
                                case "LEARNED":
                                    inputStr.append("1 ");
                                    break;
                                case "LEARN_FAILED":
                                    inputStr.append("2 ");
                                    break;
                            }

                            inputStr.append(planTemp.getCpa_bid() + " " + planTemp.getBudget() + " ");
                            inputStr.append(collectPlanStatus.containsKey(planTemp.getId()) ? collectPlanStatus.get(planTemp.getId()).get(0).getStatus() : "0" + "\n");//状态值
                        }
                        String bidInputPath = pythonPath + SnowflakeIdWorkerUtil.generateId() + pythonSuffix;
                        File bidInputFile = new File(bidInputPath);
                        int bidResult = BufferedWriterUtil.writerIntoFile(bidInputFile, inputStr.toString());
                        if (bidResult == AccountConstant.FAIL) {
                            log.error(bidInputFile.getAbsolutePath() + "输入文件生成失败");
                            return;
                        }

//                        计划id	创意id	消耗	展示	平均千次展现	点击数	平均点击单价	点击率	转化数	转化成本	转化率
                        //（创意数据）计划id，创意id，点击数，点击率~(累加的)
                        StringBuilder creativeStr=new StringBuilder();
                        for (OceanengineReportCreativeInfo.DataBean.ListBean creativeTemp : reportCreativeList) {
                            creativeStr.append(creativeTemp.getAd_id() + " " + creativeTemp.getCreative_id() + " "+creativeTemp.getCost()
                                    +" "+creativeTemp.getShow()+" "+creativeTemp.getAvg_show_cost()+" "+creativeTemp.getClick()+" "+creativeTemp.getAvg_click_cost()+" "+creativeTemp.getCtr()+" "+
                                    creativeTemp.getConvert()+" "+creativeTemp.getConvert_cost()+" "+creativeTemp.getConvert_rate()+"\n");
                        }


                        String creativeInputPath = pythonPath + SnowflakeIdWorkerUtil.generateId() + pythonSuffix;
                        File creativeInputFile = new File(creativeInputPath);
                        int creativeResult = BufferedWriterUtil.writerIntoFile(creativeInputFile, creativeStr.toString());
                        if (creativeResult == AccountConstant.FAIL) {
                            log.error(creativeInputFile.getAbsolutePath() + "输入文件生成失败");
                            return;
                        }

                        log.info("智能启停开始了,,,,,执行toufang。lingo=====");


//                        String[] arguments = new String[] {"C:\\Users\\EDZ\\AppData\\Local\\Programs\\Python\\Python37\\python", "D:\\ylyq\\PlanContorModel\\Main.py",
//                                planInputFile.getAbsolutePath(),bidInputFile.getAbsolutePath(),creativeInputFile.getAbsolutePath()};
                        String resultPython = PythonUtil.execPython("D:\\ylyq\\PlanContorModel\\Main.py", planInputFile.getAbsolutePath(),bidInputFile.getAbsolutePath(),
                                creativeInputFile.getAbsolutePath());


                        List<Long> stopPlanid = new ArrayList<>();//需要暂停的计划id集合
                        List<UpdatePlanBidInfoRequest.DataBean> bids = new ArrayList<>();//需要修改出价的计划id集合
                        List<UpdatePlanBudgetInfoRequest.DataBean> budgets = new ArrayList<>();//需要修改预算的计划id集合
//                        String pathPlan = "lingo/toufan.lng";
//                        File resultFilePlan = iLingoService.excuteLingo(dataStr.toString(), pathPlan);
                        File resultFilePlan = new File(resultPython);
                        if (resultFilePlan != null) {
                            log.info("智能启停开始了,,,,,执行toufang。lingo成功=====" + resultFilePlan.getAbsolutePath());

                            List<YlyqPlanStatus> ylyqPlanStatusList = new ArrayList<>();

                            String path = "";
                            File file = new File(path);
                            StringBuilder result = new StringBuilder();
                            try{
                                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件

                                String s = null;
                                while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                                    result.append(s+"~");
                                }
                                br.close();
                            }catch(Exception e){
                                e.printStackTrace();
                            }

                            String[] resultPlanList = result.toString().split("~");
                            for (String tempResultPlan:resultPlanList){
                                //计划id，执行操作（0：不操作，1：修改预算，2：修改出价，3修改预算和出价，4新建计划，5修改出价并新建计划，6暂停，7暂停并新建，8修改出价并复制计划，9暂停并复制计划，10复制计划），出价，预算，状态值~
                                String[] split = tempResultPlan.split(",");
                                //计划id	操作码	出价	预算	状态码
                                Long planid = Long.parseLong(split[0]);
                                String zhuangtai = split[1];
                                String chujia = split[2];
                                String yusuan = split[3];
                                String state = split[4];


                                if (collectPlanStatus.containsKey(planid)) {
                                    YlyqPlanStatus ylyqPlanStatus = new YlyqPlanStatus();
                                    ylyqPlanStatus.setId(collectPlanStatus.get(planid).get(0).getId());
                                    ylyqPlanStatus.setPlanId(planid);
                                    ylyqPlanStatus.setStatus(state);
                                    ylyqPlanStatusList.add(ylyqPlanStatus);
                                } else {
                                    YlyqPlanStatus ylyqPlanStatus = new YlyqPlanStatus();
                                    ylyqPlanStatus.setPlanId(planid);
                                    ylyqPlanStatus.setStatus(state);
                                    ylyqPlanStatusList.add(ylyqPlanStatus);
                                }


                                switch (zhuangtai) {
                                    case "0"://不做任何操作
                                        break;
                                    case "1"://修改预算
                                        budgets.add(new UpdatePlanBudgetInfoRequest.DataBean(planid, Double.parseDouble(yusuan)));
                                        break;
                                    case "2"://修改出价
                                        bids.add(new UpdatePlanBidInfoRequest.DataBean(planid, Double.parseDouble(chujia)));
                                        break;
                                    case "3":
                                        //修改出价
                                        bids.add(new UpdatePlanBidInfoRequest.DataBean(planid, Double.parseDouble(chujia)));
                                        //修改预算
                                        budgets.add(new UpdatePlanBudgetInfoRequest.DataBean(planid, Double.parseDouble(yusuan)));
                                        break;
                                    case "4"://新建计划
                                        //查询衍生计划的内容，用当前的衍生计划的内容作为新计划的内容进行投放
                                        creatNewPlan(advertiser,groupId, userId);
                                        break;
                                    case "5"://修改出价并新建计划
                                        bids.add(new UpdatePlanBidInfoRequest.DataBean(planid, Double.parseDouble(chujia)));
                                        creatNewPlan(advertiser,groupId, userId);
                                        break;
                                    case "6"://暂停计划
                                        stopPlanid.add(planid);
                                        break;
                                    case "7"://暂停并新建
                                        stopPlanid.add(planid);
                                        creatNewPlan(advertiser,groupId, userId);
                                        break;
                                    case "8"://修改出价并复制计划
                                        bids.add(new UpdatePlanBidInfoRequest.DataBean(planid, Double.parseDouble(chujia)));
                                        copyPlan(collectPlanInfo, userId, advertiser, planid);
                                        break;
                                    case "9"://暂停并复制计划
                                        stopPlanid.add(planid);
                                        copyPlan(collectPlanInfo, userId, advertiser, planid);
                                        break;
                                    case "10"://复制计划
                                        copyPlan(collectPlanInfo, userId, advertiser, planid);
                                        break;
                                }
                            }
                            iYlyqPlanStatusService.saveOrUpdateBatch(ylyqPlanStatusList);
                        }

                        //修改出价
                        if (!bids.isEmpty()) {
                            log.info("智能启停开始了,,,,,修改出价=====");
                            //因为一次批量操作，最多处理100个id
                            int k = 0;
                            while (bids.size() > 100 * k) {
                                List<UpdatePlanBidInfoRequest.DataBean> bidsTemp;
                                if (bids.size() > 100 * (k + 1)) {
                                    bidsTemp = bids.subList(k * 100, 100 * (k + 1));
                                } else {
                                    bidsTemp = bids.subList(k * 100, bids.size());
                                }

                                OceanengineUpdatePlanBidResult oceanengineUpdatePlanBidResult = iOceaneginePlanService.updateBatchPlanBid(new UpdatePlanBidInfoRequest((Long) advertiser, bidsTemp));
                                if (oceanengineUpdatePlanBidResult.getCode() == AccountConstant.SUCCESS) {
                                    log.info("advertiserid==" + advertiser + "planid====" + bidsTemp.toString() + "updateBatchPlanBid success");
                                } else {
                                    log.error("advertiserid==" + advertiser + "planid====" + bidsTemp.toString() + "updateBatchPlanBid fail");
                                }
                                k++;
                            }
                        }

                        //修改预算
                        if (!budgets.isEmpty()) {
                            log.info("智能启停开始了,,,,,修改预算=====");
                            //因为一次批量操作，最多处理100个id
                            int j = 0;
                            while (budgets.size() > 100 * j) {
                                List<UpdatePlanBudgetInfoRequest.DataBean> budgetsTemp;
                                if (budgets.size() > 100 * (j + 1)) {
                                    budgetsTemp = budgets.subList(j * 100, 100 * (j + 1));
                                } else {
                                    budgetsTemp = budgets.subList(j * 100, budgets.size());
                                }

                                OceanengineUpdatePlanBudgetResult oceanengineUpdatePlanBudgetResult = iOceaneginePlanService.updateBatchPlanBudget(new UpdatePlanBudgetInfoRequest((Long) advertiser, budgetsTemp));
                                if (oceanengineUpdatePlanBudgetResult.getCode() == AccountConstant.SUCCESS) {
                                    log.info("advertiserid==" + advertiser + "planid====" + budgetsTemp.toString() + "updateBatchPlanBudget success");
                                } else {
                                    log.error("advertiserid==" + advertiser + "planid====" + budgetsTemp.toString() + "updateBatchPlanBudget fail");
                                }
                                j++;
                            }

                        }

                        //暂停计划
                        if (!stopPlanid.isEmpty()) {
                            log.info("智能启停开始了,,,,,暂停计划=====");
//因为一次批量操作，最多处理100个id
                            int i = 0;
                            while (stopPlanid.size() > 100 * i) {
                                List<Long> planIds;
                                if (stopPlanid.size() > 100 * (i + 1)) {
                                    planIds = stopPlanid.subList(i * 100, 100 * (i + 1));
                                } else {
                                    planIds = stopPlanid.subList(i * 100, stopPlanid.size());
                                }


                                OceanengineUpdatePlanStateResult disable = iOceaneginePlanService.updateBatchPlanState(new UpdatePlanStateInfoRequest(advertiser, planIds.toArray(new Long[planIds.size()]), "disable"));
                                if (disable.getCode() == AccountConstant.SUCCESS) {
                                    //暂停的计划要移除智能启停
                                    QueryWrapper<YlyqPlanStopStart> removePlan = new QueryWrapper<>();
                                    removePlan.in("plan_id", planIds);
                                    removePlan.eq("advertiser_id", advertiser);
                                    iYlyqPlanStopStartService.remove(removePlan);
                                    log.info("智能启停开始了,,,,,暂停计划=====advertiserid==" + advertiser + "planid====" + planIds.toString() + "暂停成功，并成功从易量删除");
                                } else {
                                    log.error("advertiserid==" + advertiser + "planid====" + planIds.toString() + "stop fail");
                                }
                                i++;
                            }

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();
        log.info("智能启停结束了=====");
    }

    private void creatNewPlan(Long advertiser,Long groupId, String userId) throws Exception {
        GeneratePlansRequest generatePlansRequest = (GeneratePlansRequest) redisUtils.get(String.valueOf(advertiser));
        if (generatePlansRequest != null) {
            ResponseData responseData = iOceaneginePlanService.generatePlans(generatePlansRequest);
            if (responseData.getCode() == ResponseData.Result.SUCCESS.getCode()) {
                Vector<ResultPlan> resultPlans = (Vector<ResultPlan>) responseData.getData();

                if (resultPlans != null && !resultPlans.isEmpty()) {
                    //创建组
//                    CreateGroupInfoRequest createGroupInfoRequest = new CreateGroupInfoRequest();
////                budget:budget,（生成计划你返回的）
////                advertiser_id:_this.advertiserId,(广告主id)
////                        budget_mode:'BUDGET_MODE_INFINITE',
////                        campaign_name:campaignName,（生成计划你返回的）
////                landing_type:'LINK'
//                    createGroupInfoRequest.setAdvertiser_id(advertiser);
//                    createGroupInfoRequest.setBudget(resultPlans.get(0).getBudget());
//                    createGroupInfoRequest.setBudget_mode("BUDGET_MODE_INFINITE");
//                    createGroupInfoRequest.setCampaign_name(resultPlans.get(0).getGroupName());
//                    createGroupInfoRequest.setLanding_type(generatePlansRequest.getShopFlag()==0?"GOODS":"LINK");
//                    OceanengineCreateGroupResult createGroupResult = iOceanegineGroupService.createGroup(createGroupInfoRequest);
//                    if (createGroupResult.getCode().intValue() == AccountConstant.SUCCESS) {
                    //创建计划
                    List<YlyqPlanStopStart> ylyqPlanStopStartList = new ArrayList<>();
                    for (ResultPlan resultPlan : resultPlans) {

                        CreatePlanInfoRequest createPlanInfoRequest = new CreatePlanInfoRequest();
                        createPlanInfoRequest.setAdvertiser_id(advertiser);
                        createPlanInfoRequest.setBudget(resultPlan.getRys());
                        createPlanInfoRequest.setBudget_mode("BUDGET_MODE_DAY");
                        createPlanInfoRequest.setName(resultPlan.getPlanName());
                        createPlanInfoRequest.setAge(resultPlan.getAge().split(","));
                        createPlanInfoRequest.setGender(resultPlan.getSex());
                        createPlanInfoRequest.setDistrict("CITY");
                        createPlanInfoRequest.setCity(Arrays.stream(resultPlan.getArea()).map(ResultPlan.AreaBean::getCityID).collect(Collectors.toList()).toArray(new Long[resultPlan.getArea().length]));
//                            createPlanInfoRequest.setCampaign_id(createGroupResult.getData().getCampaign_id());
                        createPlanInfoRequest.setCampaign_id(groupId);
                        createPlanInfoRequest.setDelivery_range(resultPlan.getDelivery_range());
                        createPlanInfoRequest.setFlow_control_mode("FLOW_CONTROL_MODE_FAST");
                        createPlanInfoRequest.setPricing("PRICING_OCPM");
                        createPlanInfoRequest.setConvert_id(resultPlan.getCovertId());
                        createPlanInfoRequest.setSchedule_type("SCHEDULE_FROM_NOW");
                        createPlanInfoRequest.setCpa_bid(resultPlan.getChujia());
                        createPlanInfoRequest.setExternal_url(resultPlan.getExternal_url());
                        createPlanInfoRequest.setChooseUrl(resultPlan.getChooseUrl());
                        createPlanInfoRequest.setChooseCodeUrl(resultPlan.getChooseCodeUrl());
                        createPlanInfoRequest.setInterest_action_mode(resultPlan.getInteset());
                        createPlanInfoRequest.setHide_if_converted(resultPlan.getHide_if_converted());
                        createPlanInfoRequest.setLocation_type("ALL");
//                    advertiser_id: _this.advertiserId,//广告主id
//                            budget: item.rys,//广告预算
//                            budget_mode: 'BUDGET_MODE_DAY',//广告预算类型
//                            name: item.planName,//广告名称
//                            age: age,//受众年龄区间
//                            gender: item.sex,//受众受众性别
//                            district:'CITY',//地域类型
//                            city:city,//地域定向城市或者区县列表
//                            campaign_id: campaign_id,//广告组id
//                            delivery_range:item.delivery_range,//投放范围
//                            flow_control_mode: 'FLOW_CONTROL_MODE_FAST',  //广告投放速度类型
//                            pricing:'PRICING_OCPM',//计划出价类型
//                            convert_id:item.covertId,//转化id
//                            schedule_type:'SCHEDULE_FROM_NOW',//广告投放时间类型A
//                            cpa_bid:item.chujia,//出价
//                            external_url:item.external_url,//广告落地页链接
//                            chooseUrl:item.chooseUrl,//商品图片
//                            chooseCodeUrl:item.chooseCodeUrl,//条形码图片
//                            interest_action_mode:item.inteset,//行为兴趣
//                            hide_if_converted:item.hide_if_converted,//过滤已转化用户
//                            location_type:'ALL'//受众位置类型
                        OceanengineCreatePlanResult planResult = iOceaneginePlanService.createPlan(createPlanInfoRequest);
                        if (planResult.getCode() == AccountConstant.SUCCESS) {
                            //创建创意
                            ResultPlan.CreativeBean creativeBean = resultPlan.getCreativeBean();

//                                ad_keywords:creativeBean.cybq,//创意标签
//                                        title_list:creativeBean.cybt,//创意标题
//                                        third_industry_id:creativeBean.cyfl,//创意分类-三级行业
//                                        creative_material_mode:creativeBean.cyfs,//创意类型
//                                        creative_display_mode:creativeBean.cyzx,//创意展现方式
//                                        is_comment_disable:creativeBean.ggpl,//是否关闭评论
//                                        smart_inventory:creativeBean.ggwz, //广告位置
//                                        image_list:creativeBean.image_list,//素材信息
//                                        source:creativeBean.ly,//创意来源
//                                        ies_core_user_id:creativeBean.ppzy, //品牌主页
//                                        button_text:creativeBean.xdhz,//行动号召
//                                        is_presented_video:creativeBean.zdscspsc, //自动生成视频素材
//                                        generate_derived_ad:creativeBean.zycyysjh,//最优创意衍生计划
//                                        ad_id: (item.data.ad_id).toString(),//计划ID
//                                        advertiser_id: _this.advertiserId,//广告主ID
//                                        inventory_type:creativeBean.inventory_type,//创意投放位置
//                                        creatives:[],//自定义素材信息
                            CreateCreativeRequest createCreativeRequest = new CreateCreativeRequest();
                            createCreativeRequest.setAd_keywords(creativeBean.getCybq().toArray(new String[creativeBean.getCybq().size()]));
                            createCreativeRequest.setTitle_list(creativeBean.getCybt());
                            createCreativeRequest.setThird_industry_id(creativeBean.getCyfl());
                            createCreativeRequest.setCreative_material_mode(creativeBean.getCyfs());
                            createCreativeRequest.setCreative_display_mode(creativeBean.getCyzx());
                            createCreativeRequest.setIs_comment_disable(creativeBean.getGgpl());
                            createCreativeRequest.setSmart_inventory(creativeBean.getGgwz());
                            createCreativeRequest.setImage_list(creativeBean.getImage_list());
                            createCreativeRequest.setSource(creativeBean.getLy());
                            createCreativeRequest.setIes_core_user_id(creativeBean.getPpzy());
                            createCreativeRequest.setButton_text(creativeBean.getXdhz());
                            createCreativeRequest.setIs_presented_video(creativeBean.getZdscspsc().longValue());
                            createCreativeRequest.setGenerate_derived_ad(creativeBean.getZycyysjh().longValue());
                            createCreativeRequest.setAd_id(planResult.getData().getAd_id());
                            createCreativeRequest.setAdvertiser_id(advertiser);
                            createCreativeRequest.setInventory_type(creativeBean.getInventory_type());
                            createCreativeRequest.setCreatives(new ArrayList<>());
                            OceanengineCreateCreativeResult creativeResult = iOceanegineCreativeService.createCreative(createCreativeRequest);


                            //保存计划至智能启停
                            YlyqPlanStopStart ylyqPlanStopStart = new YlyqPlanStopStart();
                            ylyqPlanStopStart.setUserId(userId);
//                                ylyqPlanStopStart.setGroupId(createGroupResult.getData().getCampaign_id());
                            ylyqPlanStopStart.setGroupId(groupId);
                            ylyqPlanStopStart.setAdvertiserId(advertiser);
                            ylyqPlanStopStart.setPlanId(planResult.getData().getAd_id());
//                                    advertiserId: _this.advertiserId, //广告主ID
//                                            groupId: campaign_id, //广告组的id
//                                            planId: item.data.ad_id, //要智能启停计划的id
//                                            userId:localStorage.getItem('userId') //用户ID
                            ylyqPlanStopStartList.add(ylyqPlanStopStart);
                        }
                    }

                    //保存自动批量生成计划的组信息
                    YlyqGroupInfo ylyqGroupInfo = new YlyqGroupInfo();
//                                advertiserId: this.advertiserId, //广告主id
//                                        chooseCodeUrl: ruleForm.chooseCodeUrl, //商品码url
//                                        chooseUrl:  ruleForm.chooseUrl, //商品url
//                                        groupId: campaign_id, //广告组的id
//                                        priceForm: ruleForm.priceForm, //单个表单信息价值
//                                        groupName:groupName //广告组的名字
                    ylyqGroupInfo.setAdvertiserId(advertiser);
                    ylyqGroupInfo.setChooseCodeUrl(resultPlans.get(0).getChooseCodeUrl());
                    ylyqGroupInfo.setChooseUrl(resultPlans.get(0).getChooseUrl());
//                        ylyqGroupInfo.setGroupId(createGroupResult.getData().getCampaign_id());
                    ylyqGroupInfo.setGroupId(groupId);
                    ylyqGroupInfo.setPriceForm(resultPlans.get(0).getPriceForm());
                    iYlyqGroupInfoService.save(ylyqGroupInfo);

                    if (!ylyqPlanStopStartList.isEmpty())
                        iYlyqPlanStopStartService.insertBatch(ylyqPlanStopStartList);
//                    }
                }
            }
        }
    }

    private void copyPlan(Map<Long, List<OceanenginePlanInfo.DataBean.ListBean>> collectPlanInfo, String userId, Long advertiser, Long planid) {
        log.info("智能启停开始了,,,,,衍生计划=====");
        OceanenginePlanInfo.DataBean.ListBean planOld = collectPlanInfo.get(planid).get(0);
        //新增两条计划。年龄扩大（先往上加，如果满了，往下加），标题全换，创意标签减少2个，一条出价降低8%，一条出价减低12%
        String[] age = planOld.getAudience().getAge();
        if (null == age || age.length == 0) {//不限的情况下
            return;
        }
        List<String> ageListNew = new ArrayList<>(Arrays.asList(age));
        List<Integer> ageEumn = new ArrayList<>();
        for (String temp : age) {
            switch (temp) {//AGE_BETWEEN_18_23,AGE_BETWEEN_24_30,AGE_BETWEEN_31_40,AGE_BETWEEN_41_49
                case "AGE_BETWEEN_18_23":
                    ageEumn.add(1);
                    break;
                case "AGE_BETWEEN_24_30":
                    ageEumn.add(2);
                    break;
                case "AGE_BETWEEN_31_40":
                    ageEumn.add(3);
                    break;
                case "AGE_BETWEEN_41_49":
                    ageEumn.add(4);
                    break;
                case "AGE_ABOVE_50":
                    ageEumn.add(5);
                    break;
            }
        }

        ageEumn.sort(Comparator.comparingInt(Integer::intValue).reversed());// 倒序
        switch (ageEumn.get(0)) {//年龄扩大（先往上加，如果满了，往下加）
            case 1:
                ageListNew.add("AGE_BETWEEN_24_30");
                break;
            case 2:
                ageListNew.add("AGE_BETWEEN_31_40");
                break;
            case 3:
                ageListNew.add("AGE_BETWEEN_41_49");
                break;
            case 4:
                ageListNew.add("AGE_ABOVE_50");
                break;
            case 5:
                if (!ageEumn.contains(4)) {
                    ageListNew.add("AGE_BETWEEN_41_49");
                } else if (!ageEumn.contains(3)) {
                    ageListNew.add("AGE_BETWEEN_31_40");
                } else if (!ageEumn.contains(2)) {
                    ageListNew.add("AGE_BETWEEN_24_30");
                } else if (!ageEumn.contains(1)) {
                    ageListNew.add("AGE_BETWEEN_18_23");
                }
                break;
        }
        //新增两条计划。年龄扩大（先往上加，如果满了，往下加），标题全换，创意标签减少2个，一条出价降低8%，一条出价减低12%
        planOld.getAudience().setAge(ageListNew.toArray(new String[ageListNew.size()]));
        for (int i = 0; i < 2; i++) {
            //巨量新建
            CreatePlanInfoRequest createPlanInfoRequest = new CreatePlanInfoRequest();
            BeanUtils.copyProperties(planOld, createPlanInfoRequest);
            createPlanInfoRequest.setCpa_bid(i == 0 ? planOld.getCpa_bid() * 0.92 : planOld.getCpa_bid() * 0.88);
            createPlanInfoRequest.setName(createPlanInfoRequest.getName() + "_re" + i);
            OceanengineCreatePlanResult plan1 = iOceaneginePlanService.createPlan(createPlanInfoRequest);

            if (plan1.getCode() == AccountConstant.SUCCESS) {
                //易量新建
                YlyqPlanStopStart ylyqPlanStopStart = new YlyqPlanStopStart();
                ylyqPlanStopStart.setPlanId(plan1.getData().getAd_id());
                ylyqPlanStopStart.setAdvertiserId(advertiser);
                ylyqPlanStopStart.setGroupId(createPlanInfoRequest.getCampaign_id());
                ylyqPlanStopStart.setUserId(userId);
                iYlyqPlanStopStartService.save(ylyqPlanStopStart);


                //为新增的计划新建创意
                //先获取已有的创意
                CreativeDetailRequest creativeDetailRequest = new CreativeDetailRequest();
                creativeDetailRequest.setAd_id(planOld.getId());
                creativeDetailRequest.setAdvertiser_id(advertiser);
                OceanengineCreativeDetail oceanengineCreativeDetail = iOceanegineCreativeService.creativeDetail(creativeDetailRequest);


                //把已有的创意复制到createCreativeRequest，新建创意
                CreateCreativeRequest createCreativeRequest = new CreateCreativeRequest();
                BeanUtils.copyProperties(oceanengineCreativeDetail.getData(), createCreativeRequest);
                createCreativeRequest.setAd_id(plan1.getData().getAd_id());

                List<String> Ad_keywords = new ArrayList<>(Arrays.asList(createCreativeRequest.getAd_keywords()));
                if (Ad_keywords.size() > 8) {
                    Ad_keywords.remove(7);
                    Ad_keywords.remove(2);
                } else if (Ad_keywords.size() > 2) {
                    Ad_keywords = Ad_keywords.subList(2, Ad_keywords.size());
                }
                createCreativeRequest.setAd_keywords(Ad_keywords.toArray(new String[Ad_keywords.size()]));

//                                                List<String> collectTitles = createCreativeRequest.getTitle_list().stream().map(CreateCreativeRequest.TitleListBean::getTitle).collect(Collectors.toList());
//
//                                                QueryWrapper<YlyqCreativeTitle> creativeTitleQueryWrapper = new QueryWrapper<>();
//                                                creativeTitleQueryWrapper.notIn("title_name", collectTitles);
//                                                creativeTitleQueryWrapper.select("title_name", "creative_ids");
//                                                List<YlyqCreativeTitle> creativeResult = iYlyqCreativeTitleService.list(creativeTitleQueryWrapper);
//                                                if (creativeResult.size() > 5)
//                                                    creativeResult = creativeResult.subList(0, 5);
//                                                List<CreateCreativeRequest.TitleListBean> creativeTitleRequest = new ArrayList<>();
//                                                for (YlyqCreativeTitle temp : creativeResult) {
//                                                    creativeTitleRequest.add(new CreateCreativeRequest.TitleListBean(temp.getTitleName(), StringUtils.isBlank(temp.getCreativeIds()) ? null : temp.getCreativeIds().split(","), null));
//                                                }


                //创意标题
                List<CreateCreativeRequest.TitleListBean> creativeTitleRequest = new ArrayList<>();

                QueryWrapper<YlyqCreativeTitleV2> titleV2QueryWrapper = new QueryWrapper<>();
                titleV2QueryWrapper.eq("advertise_id", advertiser);
                titleV2QueryWrapper.eq("group_id", createPlanInfoRequest.getCampaign_id());
                titleV2QueryWrapper.select("title_name");
                List<Object> objectsTitles = iYlyqCreativeTitleV2Service.listObjs(titleV2QueryWrapper);
                int size = objectsTitles.size() > 5 ? 5 : objectsTitles.size();
                if (size > 0) {
                    for (int j = 0; j < size; j++) {
                        creativeTitleRequest.add(new CreateCreativeRequest.TitleListBean((String) objectsTitles.get(j), null, null));
                    }
                    createCreativeRequest.setTitle_list(creativeTitleRequest);
                    QueryWrapper<YlyqCreativeTitleV2> removeQueryWrapper = new QueryWrapper<>();
                    removeQueryWrapper.eq("advertise_id", advertiser);
                    titleV2QueryWrapper.eq("group_id", createPlanInfoRequest.getCampaign_id());
                    removeQueryWrapper.in("title_name", objectsTitles.subList(0, size));
                    iYlyqCreativeTitleV2Service.remove(removeQueryWrapper);
                }

                //创意视频素材
                QueryWrapper<YlyqCreativeVideoMaterial> videoMaterialQueryWrapper = new QueryWrapper<>();
                videoMaterialQueryWrapper.eq("advertise_id", advertiser);
                videoMaterialQueryWrapper.eq("group_id", createPlanInfoRequest.getCampaign_id());
                videoMaterialQueryWrapper.select("video_id", "material_mode");
                List<YlyqCreativeVideoMaterial> videoMaterial = iYlyqCreativeVideoMaterialService.list(videoMaterialQueryWrapper);

                if (videoMaterial != null && !videoMaterial.isEmpty()) {//不为空的情况就是当时上传的时候时通过处理碎片视频方式
                    //需要用分页优化，还有在模型投放时新增的时候，也是
                    int videoMaterialsize = videoMaterial.size() > 3 ? 3 : videoMaterial.size();
                    if (videoMaterialsize > 0) {

                        List<CreateCreativeRequest.ImageListBean> image_listOld = createCreativeRequest.getImage_list();
                        if (image_listOld != null && !image_listOld.isEmpty()) {
                            List<CreateCreativeRequest.ImageListBean> image_listNew = new ArrayList<>();

                            for (int j = 0; j < videoMaterialsize; j++) {
                                CreateCreativeRequest.ImageListBean creativeListBean = new CreateCreativeRequest.ImageListBean();
                                creativeListBean.setVideo_id(videoMaterial.get(j).getVideoId());
                                creativeListBean.setImage_id(image_listOld.get(0).getImage_id());
                                creativeListBean.setImage_mode(image_listOld.get(0).getImage_mode());
                                creativeListBean.setImage_ids(image_listOld.get(0).getImage_ids());
                                image_listNew.add(creativeListBean);
                            }
                            createCreativeRequest.setImage_list(image_listNew);

                            QueryWrapper<YlyqCreativeVideoMaterial> removeQueryWrapper = new QueryWrapper<>();
                            removeQueryWrapper.eq("advertise_id", advertiser);
                            removeQueryWrapper.eq("group_id", createPlanInfoRequest.getCampaign_id());
                            removeQueryWrapper.in("video_id", videoMaterial.subList(0, videoMaterialsize).stream().map(YlyqCreativeVideoMaterial::getVideoId).collect(Collectors.toSet()));
                            iYlyqCreativeVideoMaterialService.remove(removeQueryWrapper);
                        }
                    }
                }

                OceanengineCreateCreativeResult creative = iOceanegineCreativeService.createCreative(createCreativeRequest);
                creative.getCode();
            }
        }
    }

    /**
     * @return void
     * @Author xiaweichao
     * @Description //TODO 撞审：：：检查由智能投放的计划，把审核不通过的计划，删除后新建  1小时执行一次 * @Date 16:18 2020/8/14
     * @Param []
     **/
    @Scheduled(cron = "0 0 */1 * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    private void reCreatePlan() {
        log.info("智能检测开始了=====");
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        QueryWrapper<YlyqPlanStopStart> queryWrapperPlan = new QueryWrapper<>();
        queryWrapperPlan.select("advertiser_id", "user_id", "plan_id");
        List<YlyqPlanStopStart> listPlanStopStart = iYlyqPlanStopStartService.list(queryWrapperPlan);
        if (null == listPlanStopStart || listPlanStopStart.isEmpty())
            return;
        //list分组,根据advertiser_id分组
        Map<Long, List<YlyqPlanStopStart>> collectPlanStopStart = listPlanStopStart.stream().collect(Collectors.groupingBy(YlyqPlanStopStart::getAdvertiserId));
        for (Map.Entry<Long, List<YlyqPlanStopStart>> entry : collectPlanStopStart.entrySet()) {
            Long advertiser = entry.getKey();
            List<YlyqPlanStopStart> list = entry.getValue();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (list.isEmpty()) {
                            return;
                        }
                        String userId = list.get(0).getUserId();
                        Long[] planId = list.stream().map(YlyqPlanStopStart::getPlanId).collect(Collectors.toList()).toArray(new Long[list.size()]);

                        //在线程里保存所用的access_token。如果refresh_token 过期了就无法进行启停监控了
                        String access_token = (String) redisUtils.get("access_token" + userId);
                        if (StringUtils.isBlank(access_token)) {
                            String refresh_token = (String) redisUtils.get("refresh_token" + userId);
                            if (StringUtils.isBlank(refresh_token)) {
                                log.error("refresh_token 过期：{}", refresh_token);
                                return;
                            }
                            String accessToken = iOauthService.reFreshAccessToken(userId, refresh_token);
                            FilterContextHandler.setOceaneToken(accessToken);
                        } else {
                            FilterContextHandler.setOceaneToken(access_token);
                        }

                        //获取计划详情
                        GetPlanInfoRequest getPlanInfoRequest = new GetPlanInfoRequest();
                        getPlanInfoRequest.setAdvertiser_id(advertiser);
                        getPlanInfoRequest.setPage_size(planId.length);
                        GetPlanInfoRequest.FilteringGetPlanInfoRequest filteringGetPlanInfoRequest = new GetPlanInfoRequest.FilteringGetPlanInfoRequest();
                        filteringGetPlanInfoRequest.setIds(planId);
                        filteringGetPlanInfoRequest.setStatus("AD_STATUS_AUDIT_DENY");//审核不通过
                        getPlanInfoRequest.setFiltering(filteringGetPlanInfoRequest);
                        OceanenginePlanInfo planInfo = iOceaneginePlanService.getPlan(getPlanInfoRequest);
                        if (null == planInfo) {
                            return;
                        }
                        if (planInfo.getCode() == 40002) {//这种情况是出现在用户在巨量上手动删除的,要在易量系统中也删除
                            iYlyqPlanStopStartService.remove(new QueryWrapper<YlyqPlanStopStart>().in("plan_id", planId));
                            log.info("智能检测=====advertiserid==" + advertiser + "planid====" + Arrays.toString(planId) + "用户在巨量上手动删除，并成功从易量删除");
                            return;
                        }
                        List<OceanenginePlanInfo.DataBean.ListBean> planInfoList = planInfo.getData().getList();
                        if (null == planInfoList || planInfoList.isEmpty())
                            return;


                        List<YlyqPlanStopStart> ylyqPlanStopStartList = new ArrayList<>();
//                        List<Long> creativeIds = new ArrayList<>();


//                        for (OceanenginePlanInfo.DataBean.ListBean planDetail : planInfoList) {
                        for (int i = planInfoList.size() - 1; i > -1; i--) {
                            OceanenginePlanInfo.DataBean.ListBean planDetail = planInfoList.get(i);

                            //审核不通过重新提交，，但是拒审三次就不再提交了，数据库保存下来，供后面展示给前端
                            QueryWrapper<YlyqRefusePlan> refusePlanQueryWrapper = new QueryWrapper<>();
                            refusePlanQueryWrapper.eq("advertiser_id", advertiser);
                            refusePlanQueryWrapper.eq("group_id", planDetail.getCampaign_id());
                            refusePlanQueryWrapper.eq("plan_id_current", planDetail.getId());
                            YlyqRefusePlan ylyqRefusePlanOne = iYlyqRefusePlanService.getOne(refusePlanQueryWrapper);

                            if (ylyqRefusePlanOne != null && ylyqRefusePlanOne.getCount() == 3) {
                                planInfoList.remove(i);
                                continue;
                            } else {
                                // 巨量新建
                                log.info("智能检测开始了,,,,,巨量新建=====");
                                CreatePlanInfoRequest createPlanInfoRequest = new CreatePlanInfoRequest();
                                BeanUtils.copyProperties(planDetail, createPlanInfoRequest);
                                createPlanInfoRequest.setName(createPlanInfoRequest.getName() + "_re");
                                OceanengineCreatePlanResult planResult = iOceaneginePlanService.createPlan(createPlanInfoRequest);
                                if (planResult.getCode() == AccountConstant.SUCCESS) {
                                    if (ylyqRefusePlanOne == null) {//拒审表里不存在的，说明是第一次被拒审
                                        YlyqRefusePlan ylyqRefusePlan = new YlyqRefusePlan();
                                        ylyqRefusePlan.setAdvertiserId(advertiser);
                                        ylyqRefusePlan.setGroupId(planDetail.getCampaign_id());
                                        ylyqRefusePlan.setPlanIdStart(planDetail.getId());
                                        ylyqRefusePlan.setPlanIdCurrent(planResult.getData().getAd_id());
                                        ylyqRefusePlan.setCount(1);
                                        iYlyqRefusePlanService.save(ylyqRefusePlan);
                                    } else {//拒审表里存在的，要判断是第几次拒审，第三次就不再重建计划了
                                        ylyqRefusePlanOne.setCount(ylyqRefusePlanOne.getCount() + 1);
                                        ylyqRefusePlanOne.setPlanIdCurrent(planResult.getData().getAd_id());
                                        iYlyqRefusePlanService.updateById(ylyqRefusePlanOne);
                                    }
                                }

                                //新建计划不管成功与否，关联计划的创意都要删除
                                CreativeDetailRequest creativeDetailRequest = new CreativeDetailRequest();
                                creativeDetailRequest.setAd_id(planDetail.getId());
                                creativeDetailRequest.setAdvertiser_id(advertiser);
                                //取当前的创意详情
                                OceanengineCreativeDetail oceanengineCreativeDetail = iOceanegineCreativeService.creativeDetail(creativeDetailRequest);
//                                creativeIds.addAll(oceanengineCreativeDetail.getData().getCreatives().stream().map(OceanengineCreativeDetail.DataBean.CreativesBean::getCreative_id).collect(Collectors.toList()));

                                if (planResult.getCode() == AccountConstant.SUCCESS) {//新建计划。不管成功与否，关联计划得创意都要删除
                                    //新建创意
                                    log.info("智能检测开始了,,,,,新建创意=====");
                                    CreateCreativeRequest createCreativeRequest = new CreateCreativeRequest();
                                    BeanUtils.copyProperties(oceanengineCreativeDetail.getData(), createCreativeRequest);
                                    createCreativeRequest.setAd_id(planResult.getData().getAd_id());
                                    OceanengineCreateCreativeResult creative = iOceanegineCreativeService.createCreative(createCreativeRequest);
//                                    creative.getCode();
                                    //易量新建
                                    YlyqPlanStopStart ylyqPlanStopStart = new YlyqPlanStopStart();
                                    ylyqPlanStopStart.setPlanId(planResult.getData().getAd_id());
                                    ylyqPlanStopStart.setAdvertiserId(advertiser);
                                    ylyqPlanStopStart.setGroupId(planDetail.getCampaign_id());
                                    ylyqPlanStopStart.setUserId(userId);
                                    ylyqPlanStopStartList.add(ylyqPlanStopStart);
                                }
                            }

                        }
                        //易量新建
                        if (!ylyqPlanStopStartList.isEmpty())
                            iYlyqPlanStopStartService.insertBatch(ylyqPlanStopStartList);
                        //巨量创意删除
//                        ResponseData disable = iOceanegineCreativeService.updateCreativeState(new UpdateCreativeState(advertiser, creativeIds.toArray(new Long[creativeIds.size()]), "disable"));
//                        disable.getCode();

                        if (!planInfoList.isEmpty()) {
                            log.info("智能检测开始了,,,,,巨量删除,易量删除=====");
                            //巨量删除
//因为一次批量操作，最多处理100个id
                            int i = 0;
                            while (planInfoList.size() > 100 * i) {
                                List<OceanenginePlanInfo.DataBean.ListBean> planIds;
                                if (planInfoList.size() > 100 * (i + 1)) {
                                    planIds = planInfoList.subList(i * 100, 100 * (i + 1));
                                } else {
                                    planIds = planInfoList.subList(i * 100, planInfoList.size());
                                }

                                UpdatePlanStateInfoRequest updatePlanStateInfoRequest = new UpdatePlanStateInfoRequest();
                                updatePlanStateInfoRequest.setAdvertiser_id(advertiser);
                                updatePlanStateInfoRequest.setOpt_status("delete");
                                updatePlanStateInfoRequest.setAd_ids(planIds.stream().map(OceanenginePlanInfo.DataBean.ListBean::getId).collect(Collectors.toList()).toArray(new Long[planIds.size()]));
//                                updatePlanStateInfoRequest.setAd_ids(resultPlanIds);
                                OceanengineUpdatePlanStateResult oceanengineUpdatePlanStateResult = iOceaneginePlanService.updateBatchPlanState(updatePlanStateInfoRequest);
//                                oceanengineUpdatePlanStateResult.getCode();

                                i++;
                            }

                            //易量删除
                            Long[] resultPlanIds = planInfoList.stream().map(OceanenginePlanInfo.DataBean.ListBean::getId).collect(Collectors.toList()).toArray(new Long[planInfoList.size()]);
                            QueryWrapper<YlyqPlanStopStart> removeMap = new QueryWrapper<>();
                            removeMap.in("plan_id", resultPlanIds);
                            removeMap.eq("advertiser_id", advertiser);
                            iYlyqPlanStopStartService.remove(removeMap);
                            log.info("智能检测=====advertiserid==" + advertiser + "planid====" + Arrays.toString(resultPlanIds) + "巨量删除，并成功从易量删除");
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();
        log.info("智能检测结束了=====");
    }

    /**
     * @return void
     * @Author xiaweichao
     * @Description //TODO 定时删除无用的计划  每天1点执行
     * @Param []
     **/
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    private void deletePlan() {
        log.info("定时删除无用的计划=====");
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        QueryWrapper<YlyqPlanStopStart> queryWrapperPlan = new QueryWrapper<>();
        queryWrapperPlan.select("advertiser_id", "user_id", "group_id", "plan_id");
        List<YlyqPlanStopStart> listPlanStopStart = iYlyqPlanStopStartService.list(queryWrapperPlan);
        if (null == listPlanStopStart || listPlanStopStart.isEmpty())
            return;
        //list分组,根据advertiser_id分组
        Map<Long, List<YlyqPlanStopStart>> collectPlanStopStart = listPlanStopStart.stream().collect(Collectors.groupingBy(YlyqPlanStopStart::getAdvertiserId));
        for (Map.Entry<Long, List<YlyqPlanStopStart>> entry : collectPlanStopStart.entrySet()) {
            Long advertiser = entry.getKey();
            List<YlyqPlanStopStart> list = entry.getValue();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (null == list || list.isEmpty()) {
                            return;
                        }
                        String userId = list.get(0).getUserId();
                        //在线程里保存所用的access_token。如果refresh_token 过期了就无法进行启停监控了
                        String access_token = (String) redisUtils.get("access_token" + userId);
                        if (StringUtils.isBlank(access_token)) {
                            String refresh_token = (String) redisUtils.get("refresh_token" + userId);
                            if (StringUtils.isBlank(refresh_token)) {
                                log.error("refresh_token 过期：{}", refresh_token);
                                return;
                            }
                            String accessToken = iOauthService.reFreshAccessToken(userId, refresh_token);
                            FilterContextHandler.setOceaneToken(accessToken);
                        } else {
                            FilterContextHandler.setOceaneToken(access_token);
                        }


                        Set<Long> collect = list.stream().map(YlyqPlanStopStart::getPlanId).collect(Collectors.toSet());
                        Long[] planId = collect.toArray(new Long[collect.size()]);

                        //获取计划详情
                        GetPlanInfoRequest getPlanInfoRequest = new GetPlanInfoRequest();
                        getPlanInfoRequest.setAdvertiser_id(advertiser);
                        getPlanInfoRequest.setPage_size(planId.length);
                        GetPlanInfoRequest.FilteringGetPlanInfoRequest filteringGetPlanInfoRequest = new GetPlanInfoRequest.FilteringGetPlanInfoRequest();
                        filteringGetPlanInfoRequest.setIds(planId);
                        //所有状态的都加进来扫描
                        filteringGetPlanInfoRequest.setStatus("AD_STATUS_ALL");
                        getPlanInfoRequest.setFiltering(filteringGetPlanInfoRequest);
                        OceanenginePlanInfo planInfo = iOceaneginePlanService.getPlan(getPlanInfoRequest);
                        List<OceanenginePlanInfo.DataBean.ListBean> planInfoList = planInfo.getData().getList();
                        if (null == planInfoList || planInfoList.isEmpty()) {
                            return;
                        }

                        List<Long> noCreativePlanids = new ArrayList<>();//没有创意的计划
                        List<Long> deletePlanids = new ArrayList<>();//不在投放中和账户余额不足状态的计划
                        for (OceanenginePlanInfo.DataBean.ListBean planDetail : planInfoList) {
//                            if (planDetail.getStatus().equals("AD_STATUS_DISABLE") || planDetail.getStatus().equals("AD_STATUS_DONE")) {
//                                //暂停的、已完成的计划要移除智能启停
//                                Map<String, Object> removeMap = new HashMap<>();
//                                removeMap.put("plan_id", planDetail.getId());
//                                removeMap.put("advertiser_id", advertiser);
//                                iYlyqPlanStopStartService.removeByMap(removeMap);
//                                continue;
//                            }

                            if (planDetail.getStatus().equals("AD_STATUS_CREATE")) {//计划新建。这种状态是没有传创意的，需要删除掉
                                noCreativePlanids.add(planDetail.getId());
                                continue;
                            }

                            if (!planDetail.getStatus().equals("AD_STATUS_DELIVERY_OK") && !planDetail.getStatus().equals("AD_STATUS_BALANCE_EXCEED")) {
                                //	投放中和账户余额不足状态的是有效的,不是这两个状态的就删掉
                                deletePlanids.add(planDetail.getId());
                                continue;
                            }
                        }

                        //计划新建状态，没有创意的。要移除智能启停，并在巨量中删除
                        if (!noCreativePlanids.isEmpty()) {
                            log.info("智能启停开始了,,,,,计划新建状态，没有创意的。要移除智能启停，并在巨量中删除=====");
                            UpdatePlanStateInfoRequest updatePlanStateInfoRequest = new UpdatePlanStateInfoRequest();
                            updatePlanStateInfoRequest.setAdvertiser_id(advertiser);
                            updatePlanStateInfoRequest.setOpt_status("delete");
                            updatePlanStateInfoRequest.setAd_ids(noCreativePlanids.toArray(new Long[noCreativePlanids.size()]));
                            OceanengineUpdatePlanStateResult oceanengineUpdatePlanStateResult = iOceaneginePlanService.updateBatchPlanState(updatePlanStateInfoRequest);
                            if (oceanengineUpdatePlanStateResult.getCode() == AccountConstant.SUCCESS) {
                                QueryWrapper<YlyqPlanStopStart> removeCreative = new QueryWrapper<>();
                                removeCreative.eq("advertiser_id", advertiser);
                                removeCreative.in("plan_id", noCreativePlanids);
                                iYlyqPlanStopStartService.remove(removeCreative);
                                log.info("智能启停开始=====advertiserid==" + advertiser + "planid====" + noCreativePlanids.toString() + "计划新建状态，没有创意的。要移除智能启停，并在巨量中删除，并成功从易量删除");
                            }
                        }

                        if (!deletePlanids.isEmpty()) {
                            QueryWrapper<YlyqPlanStopStart> removeCreative = new QueryWrapper<>();
                            removeCreative.eq("advertiser_id", advertiser);
                            removeCreative.in("plan_id", deletePlanids);
                            iYlyqPlanStopStartService.remove(removeCreative);
                            log.info("智能启停开始=====advertiserid==" + advertiser + "planid====" + deletePlanids.toString() + "不在投放中和账户余额不足状态的计划，成功从易量删除");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();
        log.info("智能启停结束了=====");
    }

    /**
     * @return void
     * @Author xiaweichao
     * @Description //TODO 每天23：57执行，更新账户日预算 * @Date 10:02 2020/8/4,要在24点前执行，
     * @Param []
     **/
    @Scheduled(cron = "0 57 23 * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    private void budget() {
//        每天晚上23：59执行该模型
//
//        输入:
//        日预算~
//        周预算~
//        总预算~
//        总消耗~
//        近7天消耗~
//        今日消耗
//
//        输出：
//[状态]
//        solve_status=正常	（正常和错误表示模型的执行结果是否正常）
//        账户日预算=10		（将该数据设置为账户日预算）

        List<YlyqBudget> list = iYlyqBudgetService.list();
        if (list == null || list.isEmpty()) {
            return;
        }

//        Long[] advertiseIds = list.stream().map(YlyqBudget::getAdvertiseId).collect(Collectors.toList()).toArray(new Long[list.size()]);
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Map<Long, List<YlyqBudget>> collectBudget = list.stream().collect(Collectors.groupingBy(YlyqBudget::getAdvertiseId));
        for (Map.Entry<Long, List<YlyqBudget>> budget : collectBudget.entrySet()) {

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<YlyqBudget> listBudget = budget.getValue();
                        int budgetSize = listBudget.size();
                        if (budgetSize > 1) {//有重复的，删除，只留一条
                            List<String> removeIds = new ArrayList<>();
                            for (int i = budgetSize - 1; i > 0; i--) {
                                removeIds.add(listBudget.get(i).getId());
                                listBudget.remove(i);
                            }
                            iYlyqBudgetService.removeByIds(removeIds);
                        }

                        YlyqBudget ylyqBudget = listBudget.get(0);
                        if (ylyqBudget.getBudgetDay() == null) {
                            ylyqBudget.setBudgetDay(0.0);
                        }
                        if (ylyqBudget.getBudgetWeek() == null) {
                            ylyqBudget.setBudgetWeek(0.0);
                        }
                        if (ylyqBudget.getBudgetTotal() == null) {
                            ylyqBudget.setBudgetTotal(0.0);
                        }

                        //在线程里保存所用的access_token。如果refresh_token 过期了就无法进行启停监控了
                        String userId = ylyqBudget.getUserId();
                        String access_token = (String) redisUtils.get("access_token" + userId);
                        if (StringUtils.isBlank(access_token)) {
                            String refresh_token = (String) redisUtils.get("refresh_token" + userId);
                            if (StringUtils.isBlank(refresh_token)) {
                                log.error("refresh_token 过期：{}", refresh_token);
                                return;
                            }
                            String accessToken = iOauthService.reFreshAccessToken(userId, refresh_token);
                            FilterContextHandler.setOceaneToken(accessToken);
                        } else {
                            FilterContextHandler.setOceaneToken(access_token);
                        }

                        GetAccount accountDay = iOceanegineService.getAccountDay(new GetAccountDayRequest(new Long[]{ylyqBudget.getAdvertiseId()}));
                        if (accountDay.getCode() != AccountConstant.SUCCESS) {
                            return;
                        }

                        GetAccount.DataBean.DataListBean temp = accountDay.getData().getList().get(0);

                        if (!temp.getBudget_mode().equals(ylyqBudget.getBudgetModeDay())) {//用户在巨量手动修改了预算情况
                            ylyqBudget.setBudgetModeDay(temp.getBudget_mode());
                        }

                        if (temp.getBudget().doubleValue() != ylyqBudget.getBudgetDay().doubleValue()) {//用户在巨量手动修改了预算情况
                            ylyqBudget.setBudgetDay(temp.getBudget());
                            if (temp.getBudget().doubleValue() > ylyqBudget.getBudgetWeek().doubleValue()) {
                                ylyqBudget.setBudgetWeek(temp.getBudget());
                                if (temp.getBudget().doubleValue() > ylyqBudget.getBudgetTotal().doubleValue()) {
                                    ylyqBudget.setBudgetTotal(temp.getBudget());
                                }
                            }
                            iYlyqBudgetService.updateById(ylyqBudget);
                        }


                        StringBuilder inputStr = new StringBuilder();
                        if (temp.getBudget_mode().equals("BUDGET_MODE_INFINITE")) {//不限的情况
                            inputStr.append("999999999~\n");
                            inputStr.append("999999999~\n");
                            inputStr.append("999999999~\n");
                        } else {
                            inputStr.append(ylyqBudget.getBudgetDay() + "~\n");
                            inputStr.append(ylyqBudget.getBudgetWeek() + "~\n");
                            inputStr.append(ylyqBudget.getBudgetTotal() + "~\n");
                        }


                        QueryWrapper<YlyqGroupInfo> groupInfoQueryWrapper = new QueryWrapper<>();
                        groupInfoQueryWrapper.eq("advertiser_id", temp.getAdvertiser_id());
//                groupInfoQueryWrapper.select("group_id");
//                List<Object> groupIds = iYlyqGroupInfoService.listObjs(groupInfoQueryWrapper);
//                Long groupId = (Long) groupIds.get(0);
                        List<YlyqGroupInfo> ylyqGroupInfoList = iYlyqGroupInfoService.list(groupInfoQueryWrapper);
                        if (ylyqGroupInfoList == null || ylyqGroupInfoList.isEmpty()) {
                            log.error(temp.getAdvertiser_id() + "的广告主下没有广告组");
                            return;
                        }
                        if (ylyqGroupInfoList.size() > 1) {
                            log.error(temp.getAdvertiser_id() + "的广告主下有多个广告组");
                            return;
                        }
                        YlyqGroupInfo ylyqGroupInfo = ylyqGroupInfoList.get(0);

                        GetReportGroupRequest getReportGroupRequest = new GetReportGroupRequest();
                        getReportGroupRequest.setAdvertiser_id(temp.getAdvertiser_id());
//                        getReportGroupRequest.setStart_date(new SimpleDateFormat("YYYY-MM-DD").format(ylyqGroupInfo.getCreatedTime()));
                        getReportGroupRequest.setStart_date("2020-09-17");
                        getReportGroupRequest.setEnd_date(new SimpleDateFormat("YYYY-MM-dd").format(Calendar.getInstance().getTime()));
                        getReportGroupRequest.setPage_size(Tools.getDayPactice(getReportGroupRequest.getStart_date()) > 1000 ? 1000 : Tools.getDayPactice(getReportGroupRequest.getStart_date()));
                        getReportGroupRequest.setGroup_by(new String[]{"STAT_GROUP_BY_FIELD_STAT_TIME"});
                        GetReportGroupRequest.FilteringGetReportGroupRequest filteringGetReportGroupRequest = new GetReportGroupRequest.FilteringGetReportGroupRequest();
                        filteringGetReportGroupRequest.setCampaign_ids(new Long[]{ylyqGroupInfo.getGroupId()});
                        getReportGroupRequest.setFiltering(filteringGetReportGroupRequest);
                        OceanengineReportGroupInfo reportGroup = iOceanegineReportService.getReportGroup(getReportGroupRequest);

                        List<OceanengineReportGroupInfo.DataBean.ListBean> reportList = reportGroup.getData().getList();
                        if (reportList == null || reportList.isEmpty()) {
                            log.error(temp.getAdvertiser_id() + "的广告主下的广告组数据报表为空");
                            return;
                        }
                        //按时间重排序,今天的排在第一，最开始时间排在最后
                        Collections.sort(reportList, new Comparator<OceanengineReportGroupInfo.DataBean.ListBean>() {
                            DateFormat f = new SimpleDateFormat("yyyy-MM-dd");

                            @SneakyThrows
                            @Override
                            public int compare(OceanengineReportGroupInfo.DataBean.ListBean o1, OceanengineReportGroupInfo.DataBean.ListBean o2) {
                                return f.parse(o2.getStat_datetime()).compareTo(f.parse(o1.getStat_datetime()));
                            }
                        });
                        double costTotal = 0;
                        double costWeek = 0;
                        double costToday = reportList.get(0).getCost();
                        for (int i = 0; i < reportList.size(); i++) {
                            costTotal += reportList.get(i).getCost();
                            if (i < 7) {
                                costWeek += reportList.get(i).getCost();
                            }
                        }

                        inputStr.append(costTotal + "~\n");
                        inputStr.append(costWeek + "~\n");
                        inputStr.append(costToday);

                        log.info("更新账户日预算,,,,,执行toufang。lingo=====");

                        String pathPlan = "lingo/yusuan.lng";
                        File resultFilePlan = iLingoService.excuteLingo(inputStr.toString(), pathPlan);
                        if (resultFilePlan != null) {
                            Wini ini = new Wini(resultFilePlan);
                            String jdm = "state";

                            String zhuangtai = ini.get(jdm, "solve_status");
                            String budget = ini.get(jdm, "budgetDay");

                            //[状态]
//        solve_status=正常	（正常和错误表示模型的执行结果是否正常）
//        账户日预算=10		（将该数据设置为账户日预算）

                            if (zhuangtai.equals("success")) {
                                UpdateAccountRequest updateAccountRequest = new UpdateAccountRequest();
                                updateAccountRequest.setAdvertiser_id(temp.getAdvertiser_id());
                                if (Double.parseDouble(budget) > 1000000) {//当大于100万的时候，就认为是不限
                                    updateAccountRequest.setBudget_mode("BUDGET_MODE_INFINITE");
                                } else {
                                    updateAccountRequest.setBudget(Double.parseDouble(budget));
                                    updateAccountRequest.setBudget_mode("BUDGET_MODE_DAY");
                                }

                                Object updateAccount = iOceanegineService.updateAccount(updateAccountRequest);
                                log.info("更新账户日预算,,,,," + updateAccount.toString());
                            } else {
                                log.error("更新账户日预算,,,,,执行结果为不正常");
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
